//
//  QXStatus.m
//  QXBlog
//
//  Created by QinXin on 15/7/5.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

#import "QXStatus.h"
#import <objc/runtime.h>

#define k_base_cookies_path @"/Users/labi3285/Desktop/QXBlog/Cookies"

@implementation QXStatus

+ (instancetype)unAchivedWithIdStr:(NSString *)idStr {
    NSString *path = [NSString stringWithFormat:@"%@/%@", k_base_cookies_path, idStr];
    return [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}

- (void)achiveToIdPath {
    NSString *path = [NSString stringWithFormat:@"%@/%@", k_base_cookies_path, self.idstr];
    [NSKeyedArchiver archiveRootObject:self toFile:path];
}

+ (instancetype)statusWithDic:(NSDictionary *)dic {
    return [[self alloc] initWithDic:dic];
}

- (instancetype)initWithDic:(NSDictionary *)dic {
    if (self = [super init]) {
        for (NSString *key in dic) {
            if ([[QXStatus properties] containsObject:key]) {
                
                [self setValue:dic[key] forKey:key];
            }
        }
    }
    return self;    
}

/// 描述，用于调试
- (NSString *)description {
    NSDictionary *dic = [self dictionaryWithValuesForKeys:[QXStatus properties]];
    return [NSString stringWithFormat:@"QXUser: %@", dic];
}

/// 动态取得所有属性（固定写法）
+ (NSArray *)properties {
    unsigned int propertyCount = 0;
    objc_property_t *propertyList = class_copyPropertyList([self class], &propertyCount);
    NSMutableArray *marr = [NSMutableArray arrayWithCapacity:propertyCount];
    for (int i = 0; i < propertyCount; i++) {
        objc_property_t property = propertyList[i];
        const char *cName = property_getName(property);
        NSString *ocName = [NSString stringWithUTF8String:cName];
        [marr addObject:ocName];
    }
    free(propertyList);
    return marr.copy;
}

#pragma mark - NSCoding
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder {
    if (self = [super init]) {
        for (NSString *key in [QXStatus properties]) {
            [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
        }
    }
    return self;
}
- (void)encodeWithCoder:(nonnull NSCoder *)aCoder {
    for (NSString *key in [QXStatus properties]) {
        [aCoder encodeObject:[self valueForKey:key] forKey:key];
    }
}

@end
